﻿using System;
using System.Drawing;
using System.IO;
using Newtonsoft.Json;

namespace ImageVisualizer
{
    public class ImageConverter : JsonConverter<Image>
    {
        public override Image ReadJson(JsonReader reader, Type objectType, Image existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var base64String = reader.Value as string;
            if(string.IsNullOrEmpty(base64String))
                return null;

            byte[] imageBytes = Convert.FromBase64String(base64String);
            using(var ms = new MemoryStream(imageBytes))
            {
                return new Bitmap(ms);
            }
        }

        public override void WriteJson(JsonWriter writer, Image value, JsonSerializer serializer)
        {
            using(var ms = new MemoryStream())
            {
                value.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                string base64 = Convert.ToBase64String(ms.ToArray());
                writer.WriteValue(base64);
            }
        }
    }
}